from flask import Blueprint, request, redirect, url_for, jsonify, render_template, session
from models import *
from exts import db
import math

global bookall


book_bp = Blueprint("book_manage", __name__, url_prefix="/")

@book_bp.route('/home', methods=['GET'])
def books_getall():
    session['search_bookname'] = ""
    session['search_bookisbn'] = ""
    session['search_bookauthor'] = ""
    all_book = BookModel.query.filter_by(isdeleted=1).all()
    uname = session['user_name']
    usr = UserModel.query.filter_by(username=uname).first()
    global bookall
    bookall = list(all_book)
    session['booknum'] = len(bookall)
    session['pages'] = math.ceil(session['booknum'] / 10)
    books = bookall[:10]
    if session['power'] != 0:
        canborrow = {}
        for x in books:
            if x in usr.borrow:
                canborrow[x.bookisbn] = 0
            else:
                canborrow[x.bookisbn] = 1
        return render_template("reader-main.html", nowpage=1, books=books, canborrow=canborrow)
    else:
        return render_template("admin-book-manage.html", nowpage=1, books=books,)


# 翻页
@book_bp.route('/home/<page>', methods=['GET'])
def turn_page(page):
    page = int(page)
    max_num = min(session['booknum'], (page*10))
    global bookall
    books = bookall[(page-1) * 10:max_num]
    if session['power'] != 0:
        uname = session['user_name']
        usr = UserModel.query.filter_by(username=uname).first()
        canborrow = {}
        for x in books:
            if x in usr.borrow:
                canborrow[x.bookisbn] = 0
            else:
                canborrow[x.bookisbn] = 1
        return render_template("reader-main.html", nowpage=1, books=books, canborrow=canborrow)
    else:
        return render_template("admin-book-manage.html", nowpage=page, books=books)


@book_bp.route('/home/turn', methods=['POST'])
def jump_page():
    page = request.values.get('page')
    if page == None:
        page = "1"
    print(1111)
    return turn_page(page)


# 查询
@book_bp.route('/home/search', methods=['POST'])
def search():
    bookname = request.values.get('bookname')
    bookisbn = request.values.get('bookisbn')
    bookauthor = request.values.get('bookauthor')
    session['search_bookname'] = bookname
    session['search_bookisbn'] = bookisbn
    session['search_bookauthor'] = bookauthor
    print(bookname)
    bookall = BookModel.query.filter(BookModel.bookname.contains(bookname), BookModel.bookisbn.contains(bookisbn), BookModel.author.contains(bookauthor), BookModel.isdeleted.in_([1])).all()
    session['booknum'] = len(bookall)
    session['pages'] = math.ceil(session['booknum'] / 10)
    books = bookall[:10]
    if session['power'] != 0:
        uname = session['user_name']
        usr = UserModel.query.filter_by(username=uname).first()
        canborrow = {}
        for x in books:
            if x in usr.borrow:
                canborrow[x.bookisbn] = 0
            else:
                canborrow[x.bookisbn] = 1
        return render_template("reader-main.html", nowpage=1, books=books, canborrow=canborrow)
    else:
        return render_template("admin-book-manage.html", nowpage=1, books=books)


# 获取ajax前端POST请求
@book_bp.route('/add', methods=['POST'])
def books_add():
    bookisbn_temp = request.form.get('ISBN')
    bookname_temp = request.form.get('bookname')
    author_temp = request.form.get('author')
    remainder_temp = request.form.get('remainder')
    printname_temp = request.form.get('publisher')
    print(bookisbn_temp)
    print(author_temp)

    books = BookModel.query.filter_by(bookisbn=bookisbn_temp)
    book = books.first()
    if books.count() > 0:
        if book.isdeleted == 1:
            return jsonify({'status': '0', 'errmsg': 'fail'})
        else:
            book.isdeleted = 1
            book.bookname = bookname_temp
            book.author = author_temp
            book.remainder = remainder_temp
            book.printname = printname_temp
            db.session.commit()
            return redirect(url_for("book_manage.books_getall"))
    else:
        book = BookModel(
            bookisbn=bookisbn_temp,
            bookname=bookname_temp,
            author=author_temp,
            remainder=remainder_temp,
            printname=printname_temp
        )
        db.session.add(book)
        db.session.commit()
        return redirect(url_for("book_manage.books_getall"))


@book_bp.route("/delete", methods=['POST'])
def books_delete():
    isbn = request.values.get("isbn")
    result = BookModel.query.filter_by(bookisbn=isbn).first()
    result.isdeleted = 0
    db.session.commit()
    global bookall
    for x in range(0, len(bookall)):
        if bookall[x].bookisbn == isbn:
            bookall.pop(x)
            print(x)
            break
    session['booknum'] = len(bookall)
    session['pages'] = math.ceil(session['booknum'] / 10)
    return redirect(url_for("book_manage.books_getall"))


@book_bp.route("/update", methods=['POST'])
def bookupdate_num():
    bookisbn_temp = request.form.get('ISBN')
    remainder_temp = request.form.get('remainder')
    result = BookModel.query.filter_by(bookisbn=bookisbn_temp).first()
    result.remainder = remainder_temp
    db.session.commit()
    return redirect(url_for("book_manage.books_getall"))





